package com.waitingsnow.common.share
{
import com.waitingsnow.common.share.netEaseMicroblog.NEMicroblog;
import com.waitingsnow.common.share.netEaseMicroblog.events.NEMicroblogErrorEvent;
import com.waitingsnow.common.share.netEaseMicroblog.events.NEMicroblogEvent;
import com.waitingsnow.common.share.BaseShare;
import com.waitingsnow.common.share.config.AppInfo;
import com.waitingsnow.common.share.events.ShareEvent;
import com.waitingsnow.core.debug.Logger;
import com.waitingsnow.core.service.CookieService;
import com.waitingsnow.core.util.core.ExternalUtil;

import flash.events.Event;
import flash.events.LocationChangeEvent;
import flash.media.StageWebView;
import flash.net.URLVariables;
import flash.utils.ByteArray;

/**
 * 网易微博分享 
 * @author NeilWang
 * 
 */
public class ShareToNetease extends BaseShare
{
	//==========================================================================
	//  Class variables
	//==========================================================================
	static private const NETEASE_COOKIE_NAME:String = "neteaseCookieName";
	static private const NETEASE_ACCESS_TOKEN:String = "access_token";
	static private const NETEASE_ACCESS_TOKEN_SECRET:String = "access_token_secret";
	
    //==========================================================================
    //  Class variables
    //==========================================================================
    
    //==========================================================================
    //  Constructor
    //==========================================================================
    /**
     * Constructs a new <code>ShareToNetease</code> instance.
     * 
     */
    public function ShareToNetease()
    {
        super();
		init();
    }
    
    //==========================================================================
    //  Properties
    //==========================================================================
    private var blog:NEMicroblog;
    private var so:CookieService;
    private var message:String;
	
    //==========================================================================
    //  Methods
    //==========================================================================
    /**
     * 初始化 
     * @param parames
     * 
     */    
    private function init():void
    {
        blog = new NEMicroblog(AppInfo.NETEASE_APP_KEY, AppInfo.NETEASE_APP_SECRET);
        blog.addEventListener(NEMicroblogEvent.REQUEST_TOKEN_COMPLETE, reqTokenCompleteHandler);
        blog.addEventListener(NEMicroblogEvent.OAUTH_BEGIN, oauthBeginHandler);
        blog.addEventListener(NEMicroblogEvent.ACCESS_TOKEN_COMPLETE, accessCompleteHandler);
        checkToken();
    }
    
    /**
     * 先从缓存中获取应用ID和应用密钥
     */		
    override public function checkToken():void
    {
		if (!so)
		{
			so = new CookieService(NETEASE_COOKIE_NAME);
		}
		blog.oauth_token = so.getProps(NETEASE_ACCESS_TOKEN); 
		blog.oauth_token_secret = so.getProps(NETEASE_ACCESS_TOKEN_SECRET);
        //判断是否已经授权
        if(blog.oauth_token)
        {
            //已经被授权，直接获取数据
            Logger.debug("网易账号已经被授权，直接获取数据");
        }
        else
        {
            blog.requestToken();
        }
    }  
	
	/**
	 * 分享 
	 * @param message
	 * @param picUrl
	 * 
	 */    
	override public function share(message:String = "", pic:ByteArray = null):void
	{
		this.message = message;
		blog.upload("pic.jpg", pic);
		blog.addEventListener(NEMicroblogEvent.UPLOAD_COMPLETE, uploadCompleteHandler);
		blog.addEventListener(NEMicroblogErrorEvent.UPLOAD_ERROR, uploadErrorHandler);
		blog.addEventListener(NEMicroblogEvent.UPDATE_COMPLETE, updateStatusCompleteHandler);
		blog.addEventListener(NEMicroblogErrorEvent.UPDATE_ERROR, updateStatusErrorHandler);
	}
	
	override public function dispose():void
	{
		removeWebView();
		if (so)
		{
			so.dispose();
			so = null;
		}
		if (blog)
		{
			blog.removeEventListener(NEMicroblogEvent.REQUEST_TOKEN_COMPLETE, reqTokenCompleteHandler);
			blog.removeEventListener(NEMicroblogEvent.OAUTH_BEGIN, oauthBeginHandler);
			blog.removeEventListener(NEMicroblogEvent.ACCESS_TOKEN_COMPLETE, accessCompleteHandler);
			blog = null;
		}
		super.dispose();
	}
	
    /**
     * 显示授权页面 
     * 
     */    
    private function showWebview(uri:String):void
    {
        webView = new StageWebView();
        webView.stage = stage;
        webView.viewPort = area;
        webView.loadURL(uri);
        webView.addEventListener(Event.COMPLETE, webViewCompleteHandler);
        webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, 
            webViewChangeHandler);
    }
    
    private function updateStatus(picUrl:String = ""):void
    {
        blog.update(message + picUrl);
    }
    
    /**
     * 从地址上获取verifier（授权码） 
     * @param url
     * 
     */    
    private function checkBackUrl(url:String):void
    {
        var oTemp:Boolean = true;
        Logger.debug(url);
        var urlVar:URLVariables = ExternalUtil.getURLVariables(url);
        var verifier:String = urlVar.oauth_token;
        var secret:String = urlVar.oauth_token_secret;
        if (oTemp && verifier && secret)
        {
            oTemp = false;
        }
        else if (verifier && !secret && !urlVar.oauth_callback)
        {
            blog.accessToken(verifier);
			removeWebView();
        }
        else if (!oTemp && urlVar.oauth_token && urlVar.oauth_token_secret)
        {
            
        }
    }
	
	private function removeWebView():void
	{
		if (webView)
		{
			webView.removeEventListener(Event.COMPLETE, webViewCompleteHandler);
			webView.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, 
				webViewChangeHandler);
			webView.dispose();
			webView=null;
		}
	}
    
    //==========================================================================
    //  Event Handlers
    //==========================================================================
    private function reqTokenCompleteHandler(event:NEMicroblogEvent):void
    {
        blog.authorize(AppInfo.CALL_BACK);
    }
    
    private function oauthBeginHandler(event:NEMicroblogEvent):void
    {
        showWebview(event.data.toString());
    }
    
    private function webViewChangeHandler(event:LocationChangeEvent):void
    {
        checkBackUrl(webView.location);
    }
    
    private function webViewCompleteHandler(event:Event):void
    {
        checkBackUrl(webView.location);
    }
    
    private function accessCompleteHandler(event:NEMicroblogEvent):void
    {
        dispatchEvent(new ShareEvent(ShareEvent.AUTHORIZE_COMPLETE));
    }
    
    private function uploadCompleteHandler(event:NEMicroblogEvent):void
    {
        var imgUrl:String = JSON.parse(event.data.toString()).upload_image_url;
        updateStatus(imgUrl);
    }
    
    private function updateStatusCompleteHandler(event:NEMicroblogEvent):void
    {
        dispatchEvent(new ShareEvent(ShareEvent.SHARE_COMPLETE));
    }
    
    private function uploadErrorHandler(event:NEMicroblogErrorEvent):void
    {
        Logger.error("网易分享上传图片失败");
        dispatchEvent(new ShareEvent(ShareEvent.SHARE_ERROR));
    }
    
    private function updateStatusErrorHandler(event:NEMicroblogErrorEvent):void
    {
		Logger.error("网易分享失败");
        dispatchEvent(new ShareEvent(ShareEvent.SHARE_ERROR));
    }
}
}